package cn.pconline.autoclub.service;

import cn.pconline.autoclub.entity.Album;
import cn.pconline.autoclub.entity.ClubPhoto;
import cn.pconline.autoclub.entity.Photo;
import cn.pconline.autoclub.util.DateUtils;
import cn.pconline.autoclub.util.Pager;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.danga.MemCached.MemCachedClient;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.gelivable.dao.GeliDao;
import org.gelivable.dao.GeliOrm;
import org.gelivable.dao.Mid;
import org.gelivable.dao.SqlBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class AlbumService {

    @Autowired
    private GeliDao geliDao;
    @Autowired
    private GeliOrm geliOrm;
    @Autowired
    private PagerService pagerService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private MemCachedClient mcc;

    public Album getAlbumById(long id) {
        try {
            return geliDao.find(Album.class, id);
        } catch (DataAccessException e) {
            return null;
        }
    }

    public Photo getPhotoById(long id, long albumId) {
        try {
            return geliDao.find(Photo.class, albumId, id);
        } catch (DataAccessException e) {
            return null;
        }
    }

    public Album getValidAlbum(long id) {
        Album album = getAlbumById(id);
        if (album == null || album.getStatus() == Album.STATUS_DELETE) {
            return null;
        }
        return album;
    }

    public Photo getValidPhoto(long id, long albumId) {
        Photo photo = getPhotoById(id, albumId);
        if (photo == null || photo.getStatus() == Photo.STATUS_DELETE) {
            return null;
        }
        return photo;
    }

    /**
     * 逻辑删除相册
     *
     * @param userId
     * @param clubId
     */
    public void batchDeleteAlbum(long userId, long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select album_id from ac_club_album where club_id = ").appendValue(clubId);
        sql.appendSql(" and create_by = ").appendValue(userId);
        List<Album> list = geliDao.list(Album.class, sql.getSql(), sql.getValues());
        String baseSql1 = "UPDATE %s SET status = %s WHERE create_by = %s and club_id = %s";
        String baseSql2 = "UPDATE %s SET status = %s WHERE create_by = %s and album_id = %s";
        String[] sqls = new String[list.size() + 1];
        int i = 0;
        sqls[i++] = String.format(baseSql1, "ac_club_album", Album.STATUS_DELETE, userId, clubId);
        for (Album a : list) {
            sqls[i++] = String.format(baseSql2, "ac_club_album_photo_" + a.getAlbumId() % 10, Photo.STATUS_DELETE, userId, a.getAlbumId());
        }
        geliDao.getJdbcTemplate().batchUpdate(sqls);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long create(Object o) {
        return geliDao.create(o);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long update(Object o) {
        return geliDao.update(o);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long update(Object o, String field) {
        return geliDao.update(o, field);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long deletePhoto(Photo o) {
        return geliDao.delete(o, o.getPhotoId());
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long updatePhoto(Photo photo) {
        return geliDao.update(photo);
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void updatePhotos(List<Photo> photos) {
        for (Photo p : photos) {
            geliDao.update(p);
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void deleteClubPhotos(List<ClubPhoto> clubPhotos) {
        for (ClubPhoto clubPhoto : clubPhotos) {
            geliDao.update(clubPhoto, "status");
        }
    }

    public void updateClubPhotos(List<ClubPhoto> clubPhotos) {
        for (ClubPhoto clubPhoto : clubPhotos) {
            geliDao.update(clubPhoto, "album_id");
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public long updateOrSave(Album album) {
        return album.getAlbumId() == 0 ? create(album) : update(album);
    }

    /**
     * 分页：车友会所有相册
     *
     * @param clubId
     * @param pageSize
     * @param pageNo
     * @return
     */
    public Pager<Album> pagerAllAlbumByClubId(long clubId, int pageSize, int pageNo) {
        SqlBuilder sql = new SqlBuilder();

        sql.appendSql("select album_id from ac_club_album where club_id = ").appendValue(clubId);
        sql.appendSql(" and status = ").appendValue(Album.STATUS_NORMAL);
        sql.appendSql(" order by create_at desc");
        return pagerService.pager(Album.class, sql, pageNo, pageSize);
    }

    /**
     * 车友会所有相册
     *
     * @param clubId
     * @param albumId
     * @return
     */
    public List<Album> getAllAlbumsByClubId(long clubId, long albumId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select album_id from ").appendSql(geliOrm.getTableName(Album.class)).appendSql(" where 1=1 ");
        if (clubId > 0) {
            sql.appendSql(" and club_id = ").appendValue(clubId);
        }
        if (albumId > 0) {
            sql.appendSql(" and album_id != ").appendValue(albumId);
        }
        sql.appendSql(" and status = ").appendValue(Album.STATUS_NORMAL);
        List<Album> list = null;
        try {
            list = geliDao.list(Album.class, sql.getSql(), sql.getValues());
        } catch (DataAccessException e) {
        }
        return list;
    }

    /**
     * 返回车友会默认相册
     *
     * @param clubId
     * @return
     */
    public Album getDefaultAlbum(long clubId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select album_id from ").appendSql(geliOrm.getTableName(Album.class));
        sql.appendSql(" where club_id = ").appendValue(clubId);
        sql.appendSql(" and is_default = ").appendValue(Album.ISDEFAULT_YES);
        try {
            return geliDao.list(Album.class, sql.getSql(), sql.getValues()).get(0);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public List<Photo> getAllPhotosByAlbumId(long albumId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select photo_id from ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql("  where album_id = ").appendValue(albumId);
        sql.appendSql(" and status = ").appendValue(Photo.STATUS_NORMAL);
        sql.appendSql(" order by create_at desc");
        try {
            return geliDao.list(Photo.class, albumId, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException em) {
            return Collections.emptyList();
        }
    }

    /**
     * 根据开始结束坐标查询相片
     *
     * @param albumId
     * @param start
     * @param end
     * @return
     */
    public List<Photo> listPhotosByAlbumId(long albumId, int start, int end) {
        SqlBuilder sql = new SqlBuilder();

        sql.appendSql("select photo_id from ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql("  where album_id = ").appendValue(albumId);
        sql.appendSql(" and status = ").appendValue(Photo.STATUS_NORMAL);
        sql.appendSql(" order by create_at desc limit ").appendValue(start).appendSql(",").appendValue(end);
        try {
            return geliDao.list(Photo.class, albumId, sql.getSql(), sql.getValues());
        } catch (EmptyResultDataAccessException em) {
            return Collections.emptyList();
        }
    }

    /**
     * 分页：相册下所有相片
     *
     * @param albumId
     * @param pageSize
     * @param pageNo
     * @return
     */
    public Pager<Photo> pagerAllPhotosByAlbumId(long albumId, int pageSize, int pageNo) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select photo_id from ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql(" where album_id = ").appendValue(albumId);
        sql.appendSql(" and status = ").appendValue(Photo.STATUS_NORMAL);
        sql.appendSql(" order by create_at desc, photo_id desc");
        return pagerService.pager(Photo.class, albumId, sql, pageNo, pageSize);
    }

    /**
     * 创建相册
     *
     * @param clubId
     * @param uid
     * @return
     */
    public long createAlbum(long clubId, long uid, String name, int isDefault) {
        Date date = DateUtils.getNow();

        Album album = new Album();
        album.setClubId(clubId);
        album.setName(name);
        album.setCover("http://www1.pcauto.com.cn/bbs/cargroup/2014/images/defaultphoto.png");
        album.setCreateAt(date);
        album.setUpdateAt(date);
        album.setCreateBy(uid);
        album.setIsDefault(isDefault);
        album.setStatus(Album.STATUS_NORMAL);
        // 创建默认相册
        long albumId = create(album);

        return albumId;
    }

    /**
     * 车友会相册（按创建时间倒序）
     *
     * @param clubId
     * @param num 返回数目（目前只有首页用到，num为5）
     * @return
     */
    public List<Photo> getPhotos(long clubId, int num) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select photo_id,album_id from ").appendSql(geliOrm.getTableName(ClubPhoto.class, clubId));
        sqlBuilder.appendSql(" where club_id = ").appendValue(clubId);
        sqlBuilder.appendSql(" and status = ");
        sqlBuilder.appendValue(ClubPhoto.STATUS_NORMAL);
        sqlBuilder.appendSql(" order by create_at desc limit ");
        sqlBuilder.appendValue(num);
        List<Photo> list = geliDao.getJdbcTemplate().query(sqlBuilder.getSql(), sqlBuilder.getValues(), new ResultSetExtractor<List<Photo>>() {
            @Override
            public List<Photo> extractData(ResultSet rs) throws SQLException, DataAccessException {
                List<Photo> list = new ArrayList();
                while (rs.next()) {
                    long pid = rs.getLong("photo_id");
                    long aid = rs.getLong("album_id");
                    Photo p = new Photo();
                    p.setAlbumId(aid);
                    p.setPhotoId(pid);
                    list.add(p);
                }
                return list;
            }
        });
        List<Photo> rs = new ArrayList<Photo>();
        for (Photo p : list) {
            p = getPhotoById(p.getPhotoId(), p.getAlbumId());
            if (p != null) {
                rs.add(p);
            }
        }
        return rs;
    }

    /**
     * 根据clubid获取所有车友会相片索引（按时间倒序排序）
     *
     * @param clubId
     * @return
     */
    public List<ClubPhoto> listAllPhotoByClub(long clubId) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select club_id,album_id,photo_id from ").appendSql(geliOrm.getTableName(ClubPhoto.class, clubId));
        sqlBuilder.appendSql(" where club_id = ").appendValue(clubId);
        sqlBuilder.appendSql(" and status = ");
        sqlBuilder.appendValue(ClubPhoto.STATUS_NORMAL);
        sqlBuilder.appendSql(" order by create_at desc ");
        try {
            List<ClubPhoto> list = geliDao.list(ClubPhoto.class, clubId, sqlBuilder.getSql(), sqlBuilder.getValues());
            return list;
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyList();
        }
    }

    /**
     * 车友会相片创建时间倒叙（分页）
     *
     * @param clubId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<Photo> getPhotosOrderDesc(long clubId, int pageNo, int pageSize) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select photo_id,album_id from ").appendSql(geliOrm.getTableName(ClubPhoto.class, clubId));
        sqlBuilder.appendSql(" where club_id = ").appendValue(clubId);
        sqlBuilder.appendSql(" and status = ");
        sqlBuilder.appendValue(ClubPhoto.STATUS_NORMAL);
        sqlBuilder.appendSql(" order by create_at desc");
        String sql = sqlBuilder.getSql();
        String countSql = sql.replace(sql.substring(0, sql.toLowerCase().indexOf("from")), "select count(1) ");
        int total = geliDao.count(countSql, sqlBuilder.getValues());
        sqlBuilder.appendSql(" limit ").appendValue((pageNo - 1) * pageSize).appendSql(",").appendValue(pageSize);
        Pager<Photo> pager = new Pager<Photo>();
        pager.setPageNo(pageNo);
        pager.setPageSize(pageSize);
        pager.setTotal(total);
        if (total == 0 || pageNo > pager.getPageCount() || (pageNo - 1) * pageSize < 0) {
            return null;
        }
        List<Photo> list = geliDao.getJdbcTemplate().query(sqlBuilder.getSql(), sqlBuilder.getValues(), new ResultSetExtractor<List<Photo>>() {
            @Override
            public List<Photo> extractData(ResultSet rs) throws SQLException, DataAccessException {
                List<Photo> list = new ArrayList<Photo>();
                while (rs.next()) {
                    long pid = rs.getLong("photo_id");
                    long aid = rs.getLong("album_id");
                    Photo p = new Photo();
                    p.setAlbumId(aid);
                    p.setPhotoId(pid);
                    list.add(p);
                }
                return list;
            }
        });
        List<Photo> rs = new ArrayList<Photo>();
        for (Photo p : list) {
            p = getPhotoById(p.getPhotoId(), p.getAlbumId());
            if (p != null) {
                rs.add(p);
            }
        }
        pager.setResultList(rs);
        return pager;
    }

    public String getTableName(Photo photo) {
        return geliDao.getTableName(Photo.class, photo.getAlbumId());
    }

    /**
     * 根据车友会ID统计相册总数
     *
     * @param clubId
     * @return
     */
    public int countAlbumByClubId(long clubId) {
        if (clubId < 1) {
            return 0;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ").appendSql(geliOrm.getTableName(Album.class));
        sql.appendSql(" where club_id =").appendValue(clubId);
        sql.appendSql(" and status = ").appendValue(Album.STATUS_NORMAL);
        return geliDao.count(sql.getSql(), sql.getValues());
    }

    /**
     * 根据车友会统计所有照片数量
     *
     * @param clubId
     * @return
     */
    public int countPhotoByClubId(long clubId) {
        int sum = 0;
        if (clubId < 1) {
            return sum;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select album_id from ac_club_album where club_id = ").appendValue(clubId);
        sql.appendSql(" and status = ").appendValue(Album.STATUS_NORMAL);

        List<Album> list = geliDao.list(Album.class, sql.getSql(), sql.getValues());
        if (list != null && !list.isEmpty()) {
            for (Album album : list) {
                sum += album.getQuantity();
            }
        }
        return sum;
    }

    /**
     * 实时校验相册的相片数
     */
    public void refshAlbumPhotos(long albumId, String cover) {
        if (albumId < 1) {
            return;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" select count(1) from ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql(" where album_id =").appendValue(albumId);
        sql.appendSql(" and status = ").appendValue(Photo.STATUS_NORMAL);
        int quantity = geliDao.count(sql.getSql(), sql.getValues());
        Album album = geliDao.find(Album.class, albumId);
        if (album != null) {
            if (StringUtils.isNotBlank(cover)) {
                album.setCover(cover);
            }
            album.setUpdateAt(DateUtils.getNow());
            album.setQuantity(quantity);
            geliDao.update(album, "update_at,quantity,cover");
        }
    }

    public void loadPhotoByAlbumsLimit(List<Album> albums, int limit) {
        //TODO性能优化： 可以考虑把相片最新的几张相片列表放到MC key为：AlbumId-updateAt-limit
        //这样的话，相片的删除、移动、上传就会记得更新下album的updateAt字段
        SqlBuilder sql = new SqlBuilder();

        if (albums != null && albums.size() > 0) {

            for (int i = 0; i < albums.size(); i++) {
                Album a = albums.get(i);
                if (i > 0) {
                    sql.appendSql(" union all ");
                }
                sql.appendSql("(select * from ").appendSql(geliOrm.getTableName(Photo.class, a.getAlbumId())).appendSql(" where status=");
                sql.appendValue(Photo.STATUS_NORMAL);
                sql.appendSql(" and album_id =");
                sql.appendValue(a.getAlbumId());
                sql.appendSql(" order by create_at desc ");
                sql.appendSql(" limit ");
                sql.appendValue(limit);
                sql.appendSql(")");
            }

            final List<Photo> photos = new ArrayList<Photo>();
            geliDao.getJdbcTemplate().query(sql.getSql(), sql.getValues(),
                    new RowCallbackHandler() {
                        @Override
                        public void processRow(ResultSet rs) throws SQLException {
                            if (rs != null) {
                                Photo p = new Photo();
                                p.setAlbumId(rs.getLong("album_id"));
                                p.setCreateAt(rs.getDate("create_at"));
                                p.setCreateBy(rs.getLong("create_by"));
                                p.setName(rs.getString("name"));
                                p.setPhotoId(rs.getLong("photo_id"));
                                p.setStatus(rs.getInt("status"));
                                p.setUpdateAt(rs.getDate("update_at"));
                                p.setUrl(rs.getString("url"));
                                photos.add(p);
                            }
                        }
                    });
            Map<Long, List<Photo>> map = new HashMap<Long, List<Photo>>();
            if (photos != null && photos.size() > 0) {
                for (Photo p : photos) {
                    List<Photo> list = map.get(p.getAlbumId());
                    if (list == null) {
                        list = new ArrayList<Photo>();
                        map.put(p.getAlbumId(), list);
                    }
                    list.add(p);
                }
            }
            for (Album a : albums) {
                a.setPhotos(map.get(a.getAlbumId()));
            }
        }

    }

    /**
     * 分页拿出车友会下具有相片的相册
     *
     * @param clubId
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Pager<Album> pagerLoadAlbumsByClubId(long clubId, int pageNo, int pageSize) {
        SqlBuilder sql = new SqlBuilder();

        sql.appendSql("select album_id from ac_club_album where club_id = ").appendValue(clubId);
        sql.appendSql(" and quantity>0");
        sql.appendSql(" and status = ").appendValue(Album.STATUS_NORMAL);
        return pagerService.pager(Album.class, sql, pageNo, pageSize);
    }

    public JSONObject parseAlbumJSON(Album album) {
        JSONObject object = new JSONObject();
        if (album != null) {
            object.put("clubId", album.getClubId());
            object.put("albumId", album.getAlbumId());
            object.put("cover", album.getCover160x120());
            object.put("createAt", album.getCreateAt());
            object.put("createBy", album.getCreateBy());
            object.put("isDefault", album.getIsDefault());
            object.put("name", album.getName());
            object.put("quantity", album.getQuantity());
            object.put("status", album.getStatus());
            object.put("updateAt", album.getUpdateAt());
            List<Photo> list = album.getPhotos();
            JSONArray array = new JSONArray();
            if (list != null && list.size() > 0) {
                for (Photo p : list) {
                    JSONObject o = new JSONObject();
                    o.put("albumId", p.getAlbumId());
                    o.put("createAt", p.getCreateAt());
                    o.put("createBy", p.getCreateBy());
                    o.put("name", p.getName());
                    o.put("photoId", p.getPhotoId());
                    o.put("status", p.getStatus());
                    o.put("updateAt", p.getUpdateAt());
                    o.put("url", p.getUrl());
                    o.put("url160x120", p.getUrl160x120());
                    o.put("url700x", p.getUrl700x());
                    array.add(o);
                }
            }
            object.put("photos", array);
        }
        return object;
    }

    /**
     * 批量添加相片
     *
     * @param albumId
     * @param photos
     * @return
     */
    public long[] batchCreatePhotos(long albumId, List<Photo> photos) {
        SqlBuilder sql = new SqlBuilder();
        Date date = DateUtils.getNow();
        sql.appendSql("insert into ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql(" (photo_id,album_id,name,url,create_by,create_at,update_at,width,height) value (?,?,?,?,?,?,?,?,?)");
        List<Object[]> batch = new ArrayList<Object[]>();
        long[] ids = new long[photos.size()];
        for (int i = 0; i < photos.size(); i++) {
            Photo p = photos.get(i);
            long id = geliDao.generateId(Photo.class);
            ids[i] = id;
            Object[] values = new Object[]{id, albumId, p.getName(), p.getUrl(), p.getCreateBy(), date, date, p.getWidth(), p.getHeight()};
            batch.add(values);
        }
        int count = jdbcTemplate.batchUpdate(sql.getSql(), batch).length;
        if (count > 0) {
            return ids;
        } else {
            return new long[0];
        }
    }

    /**
     * 创建车友会最新上传相片
     *
     * @param clubPhoto
     * @return
     */
    public long createClubPhoto(ClubPhoto clubPhoto) {
        return geliDao.create(clubPhoto);
    }

    /**
     * 批量创建车友会最新上传相片
     *
     * @param clubId
     * @param photos
     * @return
     */
    public int batchCreateClubPhoto(long clubId, List<ClubPhoto> photos) {
        if (photos == null || photos.isEmpty()) {
            return 0;
        }
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" insert into ").appendSql(geliOrm.getTableName(ClubPhoto.class, clubId));
        sql.appendSql(" (club_id,album_id,photo_id,create_at,create_by,status) value(?,?,?,?,?,?)");
        List<Object[]> batch = new ArrayList<Object[]>();
        for (ClubPhoto clubPhoto : photos) {
            Object[] values = new Object[]{clubId, clubPhoto.getAlbumId(), clubPhoto.getPhotoId(), clubPhoto.getCreateAt(), clubPhoto.getCreateBy(), clubPhoto.getStatus()};
            batch.add(values);
        }
        return jdbcTemplate.batchUpdate(sql.getSql(), batch).length;
    }

    public void updateClubPhoto(long clubId, long oldAlbumId, long photoId, long newAlbumId) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql(" update ").appendSql(geliOrm.getTableName(ClubPhoto.class, clubId));
        sql.appendSql(" set album_id=? where club_id= ? and album_id=? and photo_id=? and status=?");
        Object[] values = new Object[]{newAlbumId, clubId, oldAlbumId, photoId, ClubPhoto.STATUS_NORMAL};
        jdbcTemplate.update(sql.getSql(), values);
    }

    public ClubPhoto getClubPhoto(long clubId, long oldAlbumId, long photoId) {
        try {
            return geliDao.find(ClubPhoto.class, clubId, new Mid(clubId, oldAlbumId, photoId));
        } catch (EmptyResultDataAccessException e) {
        }
        return null;
    }

    /**
     * 计算相片页数
     *
     * @param albumId
     * @param pageSize
     * @return
     */
    public int countAlbumPhotoPagerNum(long albumId, int pageSize) {
        SqlBuilder sql = new SqlBuilder();
        sql.appendSql("select  count(1) from ").appendSql(geliOrm.getTableName(Photo.class, albumId));
        sql.appendSql(" where album_id = ").appendValue(albumId);
        sql.appendSql(" and status=").appendValue(Photo.STATUS_NORMAL);
        int total = geliDao.count(sql.getSql(), sql.getValues());
        return (total == 0 || pageSize <= 0) ? 1 : total / pageSize + (total % pageSize == 0 ? 0 : 1);
    }

    public void setAlbumCover(Album album, String newCover) {
        album.setCover(newCover);
        album.setUpdateAt(DateUtils.getNow());
        geliDao.update(album, "update_at, cover");
    }

    public Pager<Album> getUserAlbum(long userId, int pageNo, int pageSize) {
        SqlBuilder sqlBuilder = new SqlBuilder();
        sqlBuilder.appendSql("select album_id from ac_club_album where create_by =").appendValue(userId);
        sqlBuilder.appendSql(" order by create_at desc");
        return pagerService.pager(Album.class, sqlBuilder, pageNo, pageSize);
    }
}
